package com.dongdongshop.service.impl;

import com.dongdongshop.mapper.TbItemCatMapper;
import com.dongdongshop.pojo.TbItemCat;
import com.dongdongshop.pojo.TbItemCatExample;
import com.dongdongshop.service.CatService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@DubboService
@Service
public class CatServiceImpl implements CatService {
    @Autowired
    private TbItemCatMapper tbItemCatMapper;

    @Override
    public List<TbItemCat> listCat(Long parentId) {
        TbItemCatExample example = new TbItemCatExample();
        TbItemCatExample.Criteria criteria = example.createCriteria();
        criteria.andParentIdEqualTo(parentId);
        return tbItemCatMapper.selectByExample(example);
    }

    @Override
    public List<TbItemCat> topType(Long id) {
        List<TbItemCat> cats = topType1(id);
        return cats;
    }

    @Override
    public void addCat(TbItemCat tbItemCat) {
        tbItemCatMapper.insertSelective(tbItemCat);
    }

    @Override
    public void delCats(List<Long> ids) {
        TbItemCatExample example = new TbItemCatExample();
        TbItemCatExample.Criteria criteria = example.createCriteria();
        criteria.andIdIn(ids);
        ids.stream().forEach(id ->delItemCode(id));//将集合循环出来,给到迭代器方法删除下面的子节点.
        tbItemCatMapper.deleteByExample(example);
    }

    @Override
    public void update(TbItemCat tbItemCat) {
        tbItemCatMapper.updateByPrimaryKeySelective(tbItemCat);
    }

    @Override
    public TbItemCat toUpdate(Long id) {
        return tbItemCatMapper.selectByPrimaryKey(id);
    }

    @Override
    public TbItemCat getTypeIdById(Long id) {
        return tbItemCatMapper.selectByPrimaryKey(id);
    }

    public void delItemCode(Long id){
        TbItemCatExample example = new TbItemCatExample();
        TbItemCatExample.Criteria criteria = example.createCriteria();
        criteria.andParentIdEqualTo(id);
        List<TbItemCat> tbItemCats = tbItemCatMapper.selectByExample(example);
        if (tbItemCats== null){
            return;
        }
        tbItemCats.stream().forEach(tbItemCat -> delItemCode(tbItemCat.getId()));
        tbItemCatMapper.deleteByExample(example);
    }

    public List<TbItemCat> topType1(Long id){
        List<TbItemCat> list = new ArrayList();

        if (id == 0){
            return list;
        }
        TbItemCat tbItemCat = tbItemCatMapper.selectByPrimaryKey(id);
        list.add(tbItemCat);

        List<TbItemCat> cats = topType1(tbItemCat.getParentId());

        //将两个集合合并成一个集合
        List<TbItemCat> collect = Stream.concat(cats.stream(), list.stream()).collect(Collectors.toList());

        return collect;
    }
}
